var fs = require('fs')
var informPath = require('../config/pathConfig').informPath
var util = require('../utility/util')

var safePathCheck = util.safePathCheck

var fileName = 'informs.data'

module.exports = {
  find: function (filter, callback) {
    safePathCheck(informPath, fileName, function (exists) {
      if (exists) {
        fs.readFile(informPath + fileName, function (err, data) {
          if (err) {
            console.log('informHandler find fail. err = ' + err)
            callback(null, [])
          } else {
            if (data.length == 0) {
              data = []
            } else {
              data = JSON.parse(data)
            }
            callback(null, data)
          }
        })
      } else {
        callback(null, [])
      }
    })
  },
  insert: function (body, callback) {
    safePathCheck(informPath, fileName, function (exists) {
      if (exists) {
        var data = JSON.parse(fs.readFileSync(informPath + fileName))
      } else {
        var data = []
      }
      body.createdAt = new Date()
      data.push(body)
      data = JSON.stringify(data, null, 4)
      fs.writeFile(informPath + fileName, data, function (err) {
        if (err) {
          console.log('informHandler insert fail. err = ' + err)
          callback(null)
        } else {
          callback(null)
        }
      })
    })
  }
}
